package com.lingjtx.iot.network.handle;

import com.lingjtx.common.core.handle.EventMessageHandle;
import com.lingjtx.common.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttReportData implements EventMessageHandle {

    private final SystemServerHandler systemServerHandler;
    private final LingjtxHandler lingjtxHandler;
    private final CommunicationManagementHandler communicationManagementHandler;

    public MqttReportData(SystemServerHandler systemServerHandler,
                          LingjtxHandler lingjtxHandler,
                          CommunicationManagementHandler communicationManagementHandler) {
        this.systemServerHandler = systemServerHandler;
        this.lingjtxHandler = lingjtxHandler;
        this.communicationManagementHandler = communicationManagementHandler;
    }

    @Override
    public void process(String topic, String content) {
        if (StringUtil.isEmpty(topic) || StringUtil.isEmpty(content)) {
            log.warn("收到空的 topic 或 content，topic={}, content={}", topic, content);
            return;
        }

        String[] arr = topic.split("/");
        if (arr.length < 4) {
            log.warn("非法 topic 格式：{}", topic);
            return;
        }

        handleTopic(arr, content);
    }

    private void handleTopic(String[] arr, String content) {
        String prefix = arr[0];
        String version = arr[1];
        String productId = arr[2];
        String mac = arr[3];
        String action = arr[arr.length - 1];

        switch (prefix) {
            case "system":
                systemServerHandler.resolve(mac, action, content);
                break;
            case "lingjtx":
                lingjtxHandler.resolve(version, productId, mac, action, content);
                break;
            case "cm":
                // 通信管理机主题格式：cm/{version}/{productId}/{mac}/up/{companyId}/{action}
                // version 用于区别通讯机不同厂家，解析的 json 格式也不一样
                if (arr.length < 6) {
                    log.warn("通信管理机主题格式不正确：{}", String.join("/", arr));
                    return;
                }
                String companyId = arr[arr.length - 2];
                communicationManagementHandler.resolve(version, productId, mac, companyId, action, content);
                break;
            default:
                log.debug("未识别的 topic 前缀：{}", prefix);
                break;
        }
    }
}
